//
//  CameraView.m
//  OST
//
//  Created by mac on 13-7-18.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "CameraView.h"
#import <QuartzCore/QuartzCore.h>
#import "wis.h"
#import "Utitlity.h"

typedef struct
{
    char uuid[32];
    int cid;
    char dir[8];
} WisDevCameraCtrlCmd;

@interface CameraView ()
{
    NSString *ipUrl;
}

@property (nonatomic,retain) NSDictionary *camConfig;

@end

@implementation CameraView
@synthesize cameraImageView;

@synthesize httpRequest;
@synthesize labelTime;

-(void)dealloc
{
    [httpRequest clearDelegatesAndCancel];
    [client stop];
}

-(void)initView
{
    cameraImageView.layer.masksToBounds = YES;
    cameraImageView.layer.cornerRadius = 10;
    [cameraImageView setClipsToBounds:YES];
    
    NSLog(@"camConfig:%@",self.camConfig);
    
    UISwipeGestureRecognizer *swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                                                  action:@selector(controlCamera:)];
    swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
    [self addGestureRecognizer:swipeGestureRecognizer];
    
    UISwipeGestureRecognizer *swipeGestureRecognizer1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self                            action:@selector(controlCamera:)];
    swipeGestureRecognizer1.direction = UISwipeGestureRecognizerDirectionDown ;
    [self addGestureRecognizer:swipeGestureRecognizer1];
    
    UISwipeGestureRecognizer *swipeGestureRecognizer2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self              action:@selector(controlCamera:)];
    swipeGestureRecognizer2.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer:swipeGestureRecognizer2];
    
    UISwipeGestureRecognizer *swipeGestureRecognizer3 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(controlCamera:)];
    swipeGestureRecognizer3.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer:swipeGestureRecognizer3];
    
    [self timerFireMethod:nil];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];//使用timer定时，

}


- (void)timerFireMethod:(NSTimer*)theTimer
{
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    labelTime.text = [date stringFromDate:[NSDate date]];
}


-(void)setTheCamConfig:(NSDictionary *)thecamConfig
{
    if (self.camConfig != thecamConfig) {
      
        self.camConfig = thecamConfig;
    }
    
    if (client) {
        [client stop];
    }
    
    //NSString *url = [NSString stringWithFormat:@"http://%@:%@/%@",[camConfig objectForKey:@"ip"],[camConfig objectForKey:@"port"],@"videostream.cgi"];
    
    NSString *url = [self.camConfig objectForKey:@"Mobile"];
    //url = @"http://willis-ica.asuscomm.com:83/videostream.cgi";
    client = [[MJPEGClient alloc] initWithURL:url delegate:self timeout:-1];
    client.userName = [self.camConfig objectForKey:@"username"];
    client.password = [self.camConfig objectForKey:@"password"];
    [client start];
    
}

-(ASIHTTPRequest *)createHTTPRequest:(NSString *)baseUrl
{
    //NSString *url = [NSString stringWithFormat:@"http://%@:%@/%@",[camConfig objectForKey:@"ip"],[camConfig objectForKey:@"port"],baseUrl];
    
    NSString *url = [self.camConfig objectForKey:@"Mobile"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    request.delegate = self;
    [request setTimeOutSeconds:0];
    request.username =[self.camConfig objectForKey:@"username"];
    request.password = [self.camConfig objectForKey:@"password"];
    [request addRequestHeader:@"Connection" value:@"Keep-Alive"];
    [request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
    return request;
}



- (void)controlCamera:(UISwipeGestureRecognizer *)recognizer
{
    /*
    if (recognizer.direction == UISwipeGestureRecognizerDirectionDown) {
        self.httpRequest = [self createHTTPRequest:@"moveptz.xml?dir=up"];
    }else if (recognizer.direction == UISwipeGestureRecognizerDirectionUp) {
        self.httpRequest = [self createHTTPRequest:@"moveptz.xml?dir=down"];
    }else if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        self.httpRequest = [self createHTTPRequest:@"moveptz.xml?dir=right"];
    }else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        self.httpRequest = [self createHTTPRequest:@"moveptz.xml?dir=left"];
    }
    [self.httpRequest startAsynchronous];
    */
    
    NSString *direction = nil;
    if (recognizer.direction == UISwipeGestureRecognizerDirectionDown) {
         direction = @"Up";
    }else if (recognizer.direction == UISwipeGestureRecognizerDirectionUp) {
        direction = @"Down";
    }else if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        direction = @"Right";
    }else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        direction = @"Left";
    }

//    int count = sizeof(WisDevCameraCtrlCmd);
//    WisDevCameraCtrlCmd *cmd =(WisDevCameraCtrlCmd *) malloc(count);
//    memset((void *)cmd, 0, sizeof(count));
//    sprintf(cmd->uuid, "%s", [[[GlobalInfo sharedInstance] getUniqueID] UTF8String] );
//    cmd->cid = [[self.camConfig objectForKey:@"CID"] integerValue];
//    sprintf(cmd->dir, "%s", [direction  UTF8String]);
    
    ipUrl = [Utitlity judgeipUrl];
    
    if (ipUrl)
    {
         NSString *cameStr = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCameraControl.cgi?CID=%d&OP=%@",ipUrl,[self.camConfig getIntegerValForKey:@"CID"],direction];
        [Utitlity commonHTTPMethod:cameStr responseType:stringType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"%@",responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        WisDevCameraCtrlCmd cmd;
        memset(&cmd, 0, sizeof(WisDevCameraCtrlCmd));
        strcpy(cmd.uuid, [[[GlobalInfo sharedInstance] getUniqueID] UTF8String]);
        cmd.cid = [self.camConfig getIntegerValForKey:@"CID"];
        strcpy(cmd.dir, [direction  UTF8String]);
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_CMD_CAM_CTRL cmdLength:sizeof(WisDevCameraCtrlCmd) withData:&cmd callRecivedBlock:^(id data) {
            
            
        }];
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request{
    self.httpRequest = [self createHTTPRequest:@"moveptz.xml?dir=stop"];
    self.httpRequest.delegate = nil;
    [self.httpRequest startAsynchronous];
}


- (void) mjpegClient:(MJPEGClient*) client didReceiveImage:(UIImage*) image
{
    //NSLog(@"pic");
    [cameraImageView setImage:image];
}

- (void) mjpegClient:(MJPEGClient*) client didReceiveError:(NSError*) error
{
    NSLog(@"Error! %@", [error localizedDescription]);
}


@end
